package com.googlecode.sere.method

import com.googlecode.sere.translation.AcceptedTypes
import com.googlecode.sere.http.{HttpRequest, Status}
import com.googlecode.sere.core.{UrlRegistry, InvocationData}

class ConditionalGetMethod(uri: String, val oldEtag: String, acceptedTypes: AcceptedTypes)
  extends GetMethod(uri, acceptedTypes) {

  override def process(meta: InvocationData) = {
    val (resourceType, id) = UrlRegistry.matchUrl(uri)
    val optionalEntity = resourceType.conditionalGet(id, oldEtag, meta)
    optionalEntity match {
      case Some(entity) =>
        EntityResponse(Status.Ok, resourceType.serialize(acceptedTypes, entity))
      case None =>
        EmptyResponse(Status.NotModified)
    }
  }
}

object ConditionalGetMethod {
  // TODO: Put real etag
  def fromRequest(request: HttpRequest) = new ConditionalGetMethod(
    request.uri, "", request.acceptedTypes)
}